//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System.Collections;
using System.Collections.Specialized;
using System.IO;
using CommunityServer.Components;

namespace CommunityServer.Controls
{
	/// <summary>
	/// Summary description for ThemeManager.
	/// </summary>
	public abstract class BaseThemeManager
	{
        private NameValueCollection SkinList = new NameValueCollection();
        private Hashtable ThemeList = new Hashtable();

	    protected abstract ThemedApplicationKeyApplicationConfiguration Config {get;}

        public string SkinPath(string theme, string skin)
        {
            string key = theme + "|" + skin;

            string path = SkinList[key] as string;
            if(path == null)
            {

                path = WalkThemes(theme, skin);
                if(path != null)
                {
                       if(this.Config.EnableSkinCache)
                           SkinList[key] = path;
                }
                else
                    throw new CSException(CSExceptionType.SkinNotFound, string.Format("The Skin {0} could not be found",skin));
            }

            return path;
        }

		protected string WalkThemes(string theme, string skin)
        {
            bool found = false;
            string path = null;
            while(!found)
            {
                ThemeConfig config = GetTheme(theme);

                if(config == null)
                    break;

                if(FileExists(config.ThemeDirectoryPath, skin))
                {
                    path = Config.ThemeLocation + theme + "/"  + skin;
                    found = true;
                }
                else
                {
                    if(config.HasParent)
                        theme = config.Parent;
                    else
                        found = true;
                }
            }

            return path;
        }

        public ThemeConfig GetTheme(string name)
        {
            ThemeConfig config = ThemeList[name] as ThemeConfig;
            if(config == null)
            {
                config = ThemeConfig.Create(name, Config);
                ThemeList[name] = config;
            }

            return config;
        }

        bool FileExists(string dir, string file)
        {
            string path = Path.Combine(dir,file.Replace("/", @"\"));
            return File.Exists(path);
        }

        
	}
}
